//
//  LCDeviceTool.m
//  lechuang
//
//  Created by Mr_hi on 2023/3/24.
//  Copyright © 2023 Mooyi. All rights reserved.
//

#import "LCDeviceTool.h"
#include "sys/utsname.h"
#import <AdSupport/AdSupport.h>
#import <SystemConfiguration/CaptiveNetwork.h>

// SIM卡
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>


@implementation LCDeviceTool

+ (NSString *)getDeviceModel {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *machine = [NSString stringWithFormat:@"%s",systemInfo.machine];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"DeviceModel" ofType:@"plist"];
    NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    if ([dic objectForKey:machine]) {
        return kFORMAT(@"%@",[dic objectForKey:machine]);
    } else {
        return @"未知机型";
    }
}

+ (NSString *)deviceVersion {
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)getIdfa {
    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return idfa;
}

+ (NSString *)getMAC {
    NSString *MAC = @"00:00:00:00:00";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDic = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDic != nil) {
            NSDictionary *dic = (NSDictionary *)CFBridgingRelease(myDic);
            MAC = [dic valueForKey:@"BSSID"];
        }
    }
    return MAC;
}

+ (BOOL)isBreak {
    NSArray *jailbreak_tool_paths = @[@"/Applications/Cydia.app", @"/Library/MobileSubstrate/MobileSubstrate.dylib", @"/bin/bash", @"/usr/sbin/sshd", @"/etc/apt"];
    BOOL isYueYu1 = NO;
    for (int i=0; i<jailbreak_tool_paths.count; i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:jailbreak_tool_paths[i]]) {
            NSLog(@"The device is jail broken!");
            isYueYu1 = YES;
            break;
        }
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"User/Applications/"]) {
        NSLog(@"The device is jail broken!");
        NSArray *appList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"User/Applications/" error:nil];
        NSLog(@"%@",appList);
        isYueYu1 = YES;
    }
    
    NSURL *url = [NSURL URLWithString:@"cydia://"];
    return [[UIApplication sharedApplication] canOpenURL:url] || isYueYu1;
}

+ (void)downloadConfig {
    XWX_async_get_main(^{
        // 下载.mobileconfig描述文件
        NSLog(@"downloadConfig = %@",Url(URLConfig));
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLConfig]];
    });
}

#pragma mark - 获取系统安装的appid
+ (BOOL)deviceHaveBundleId:(NSString *)bunde {
    if (@available(iOS 12.0, *)) {
        return [self openAppWithBundleID:bunde];
    } else if (@available(iOS 11.0, *)) {
        return [self getIOS_11_DeviceOfBundleID:bunde];
    } else {
        return [self getIOS_10_DeviceOfBundleID:bunde];
    }
}

#pragma mark - 判断有没有安装该app(因为12包括12系统以上无法获取安装app的包名,所以用这种方式去判断) 注：该方法作用是打开已下载的app(适用于任何系统)
+ (BOOL)openAppWithBundleID:(NSString *)bundle {
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    NSObject * workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    BOOL isopen = [workspace performSelector:@selector(openApplicationWithBundleID:)withObject:bundle];
    return isopen;
}

// 根据软件的插件进行排重，有个缺点低版本app/某些app是没有插件的。
- (void)ChaJianPaiChong {
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
        NSObject * workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    // 列出所有plugins
    NSArray *plugins = [workspace performSelector:NSSelectorFromString(@"installedPlugins")];
    [plugins enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *pluginID = [obj performSelector:(@selector(pluginIdentifier))];
        NSLog(@"pluginID = %@",pluginID);
    }];
}

#pragma mark - 判断有没有安装该app（11系统）
+ (BOOL)getIOS_11_DeviceOfBundleID:(NSString *)bundleid {
    BOOL isok = NO;
    NSBundle *container = [NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/MobileContainerManager.framework"];
    if ([container load]) {
        Class appContainer = NSClassFromString(@"MCMAppContainer");
        id test = [appContainer performSelector:@selector(containerWithIdentifier:error:) withObject:bundleid withObject:nil];
        if (test) {
            isok = YES;
        }
    }
    return isok;
}

#pragma mark - 判断有没有安装该app（9～10系统）
+ (BOOL)getIOS_10_DeviceOfBundleID:(NSString *)bundleid {
    BOOL isok = NO;
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    NSObject *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    NSArray * bundleId = [workspace performSelector:@selector(allInstalledApplications)];
    for (NSObject * application in bundleId) {
        NSString * applicationIdentifier = [application valueForKey:@"applicationIdentifier"];
        if ([applicationIdentifier isEqualToString:bundleid]) {
            isok = YES;
            break;
        }
    }
    return isok;
}

// 获取本机运营商名称
+ (NSString *)getYunyingshang {
    // 获取本机运营商名称
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    //当前手机所属运营商名称
    NSString *mobile;
    //先判断有没有SIM卡，如果没有则不获取本机运营商
    if (!carrier.isoCountryCode) {
        NSLog(@"没有SIM卡");
        mobile = @"无运营商";
        return mobile;
    }else{
        mobile = [carrier carrierName];
        return mobile;
    }
}
// 确认是否有插SIM卡
+ (BOOL)isSIMInstalled {
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [networkInfo subscriberCellularProvider];
    if (!carrier.isoCountryCode) {
        NSLog(@"无SIM卡");
        return NO;
    }else{
        NSLog(@"存在SIM卡");
        return YES;
    }
}


@end
